<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddDialogForm">新增用户</el-button>
            </el-form-item>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="searchForm.nickname" placeholder="昵称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="nickname"
        label="昵称"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="locked"
        label="锁定状态"
        min-width="100">
        <template slot-scope="scope">
          <template v-if="scope.row.locked == 0">
            未锁定
          </template>
          <template v-else-if="scope.row.locked == 1">
            已锁定
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="所属角色"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="hotelName"
        label="所属酒店"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        min-width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="24" class="pagination-box">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageSize"
          :total="total"
          :current-page="currentPage"
          @current-change="handleCurrentChange">
        </el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="editForm.id==0?'新增用户':'修改用户'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="昵称" label-width="100px" prop="nickname">
          <el-input v-model="editForm.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="100px" prop="password">
          <el-input v-model="editForm.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="电话号码" label-width="100px" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off" maxlength="11" type="number"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" label-width="100px" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- update -->
        <!-- <el-form-item label="酒店" label-width="100px" prop="hotelIds">
          <el-select v-model="editForm.hotelIdsStr" multiple placeholder="请选择">
            <el-option
              v-for="item in hotelList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="酒店" label-width="100px" prop="hotelIds">
      
          <el-select v-model="editForm.hotelIds" multiple placeholder="请选择">
            <el-option
              v-for="item in hotelList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="申报类型" label-width="100px" prop="productTypeIds" >
          <el-cascader  style="width: 100%;"
              v-model="editForm.productTypeIds"
              :options="testProductTypeList"
              :props="{ expandTrigger: 'click', value: 'id', label: 'name' }"
              ></el-cascader>
        </el-form-item> -->
        <el-form-item label="申报类型" label-width="100px" prop="productTypeIds">
          <el-select v-model="editForm.productTypeIds"  multiple placeholder="请选择">
            <el-option
              v-for="item in testProductTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定车企" label-width="100px" prop="carEntList"v-if="editForm.role==7">
          <el-select v-model="editForm.carEntList"  filterable multiple placeholder="请选择">
            <el-option
              v-for="item in carEntList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="锁定状态" label-width="100px" prop="phoneNum">
          <el-checkbox v-model="editForm.locked">锁定</el-checkbox>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getUserList, addUser, updateUser, deleteUser} from "@/api/user";
import {getAllHotel} from "@/api/hotel";
import {getAllRole} from "@/api/role";
import {getAllTestProductTypeList} from "../../../api/test_product_type.js"
import {getAllTestCarEnterpriseList} from "../../../api/test_car_enterprise.js"

export default {
  name: "userManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      testProductTypeList: [],
      // up
      // testHotelIdsStr:[],
      carEntList:[],
      editForm: {
        id: 0,
        nickname: '',
        username: '',
        password: '',
        locked: '',
        note: '',
        role: '',
        // hotelId:'',
        hotelIds:[],
        // hotelIdsStr :'',
        phone:'',
        email:'',
        productTypeIds:'',
        carEntList:[],
      },
      editRules: {
        nickname: [{ required: true, message:"请输入昵称", trigger: 'blur'}],
        username: [{ required: true, message:"请输入用户名", trigger: 'blur'}],
        password: [{ required: true, min:6, message:"密码不能少于6个字符", trigger: 'blur'}],
        email: [{ required: true, message:"请输入邮箱", trigger: 'blur'}],
        roles: [{ required: true, message:"请选择角色", trigger: 'blur'}],
        // hotelId: [{ required: true, message:"请选择酒店", trigger: 'blur'}],
        hotelIds: [{ required: true, message:"请选择酒店", trigger: 'blur'}],
        phone: [
          { required: true, message:"请输入电话号码", trigger: 'blur'},
          { validator: validPhone, message:"手机号码格式错误", trigger: 'blur'}
        ],
      },
      loadingDiv: null,
      searchForm: {
        username: '',
        nickname: ''
      },
      roleList:[],
      hotelList:[],
    }
  },
  watch:{
    "editForm.id": function(val) {
      if(this.editForm.id == 0) {
        this.editRules['password'] = [{ required: true,min:6, message:"密码不能少于6个字符", trigger: 'blur'}];
      }else{
        this.editRules['password'] = [{ required: false,min:6, message:"密码不能少于6个字符", trigger: 'blur'}];
      }
    }
  },
  mounted() {
    this.init();
    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }
  },
  methods: {
    getAllRole(){
      getAllRole().then(res=>{
        if(res.code == 0) {
          this.$alert("获取角色列表失败", "", {dangerouslyUseHTMLString:true,type:'warning'})
            .then(()=> {
              this.editFormVisible=false;
            })
        }else if(res.code == 1) {
          this.roleList = res.data;
        }
      })

    },
    getAllHotel(){
      getAllHotel().then(res=>{
        if(res.code == 0){
          this.hotelList=res.data
        }else {
          this.$alert("获取酒店列表失败", "", {dangerouslyUseHTMLString:true,type:'warning'})
            .then(()=> {
              this.editFormVisible=false;
            })
        }
      }

      )
    },
    init(){

    // 获取所有检测产品类别
    getAllTestProductTypeList().then(res => {
      if(res.code == 1) {

        this.testProductTypeList = res.data;
        this.testProductTypeList.push({
          "id": 0,
          "name": "收车人",
        });
      }
    }).catch(res => {

    });
    },

    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = 0;
      this.editForm.email = '';
      this.editForm.role = '';
      this.editForm.productTypeIds = [];
      // this.editForm.hotelId = '';
      // this.editForm.hotelIdsStr = [];
       this.editForm.hotelIds = [];
      this.editForm.nickname = "";
      this.editForm.username = "";
      this.editForm.note = "";
      this.editForm.password = "";
      this.editForm.locked=0;
      this.editForm.phone='';
      this.editFormVisible = true;
      this.roleList = [];
      this.hotelList= [];
      this.getAllHotel();
      this.getAllRole();

      getAllTestCarEnterpriseList().then(res => {
        if(res.code == 1) {
          this.carEntList = res.data;
          // console.log(this.carEntList)
        }
      }).catch(res => {

      })
    },
    handleEdit(index, row) {
      this.getAllRole();
      this.getAllHotel();
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = row.id;
      this.editForm.nickname = row.nickname;
      this.editForm.username = row.username;
      if(row.roleId <= 0){
        this.editForm.role = "";
      }else{
        this.editForm.role = row.roleId;
      }

      // if(row.hotelId <= 0){
      //   this.editForm.hotelId = "";
      // }else{
      //   this.editForm.hotelId = row.hotelId;
      // }
//        if(row.hotelIdsStr !=null&&row.hotelIdsStr!=''){
//          //转为数组
//         this.editForm.hotelIdsStr = row.hotelIdsStr.split(",").map(Number);
//         console.log(hotelIdsStr);
// 0      }

      this.editForm.hotelIds=row.hotelIds;
        
      this.editForm.note = row.note;

      if(row.locked){
        this.editForm.locked = true;
      }else{
        this.editForm.locked = false;
      }
      this.editForm.password = "";
      this.editForm.phone=row.phone;
      this.editForm.email=row.email;
      this.editFormVisible = true;
      if(row.productTypeIds!=null&&row.productTypeIds!=''){
        this.editForm.productTypeIds = row.productTypeIds.split(",").map(Number);
       
      }
      if(row.carEntList!=null&&row.carEntList!=''){
        this.editForm.carEntList = row.carEntList.split(",").map(Number);
      }
      getAllTestCarEnterpriseList().then(res => {
        if(res.code == 1) {
          this.carEntList = res.data;
          // console.log(this.carEntList)
        }
      }).catch(res => {

      })


    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateUser
          if(this.editForm.id == 0){
            func = addUser
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(1)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },

    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除用户:"+row.nickname+"(用户名:"+row.nickname+")","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteUser({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },

    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getUserList({
        username: this.searchForm.username,
        nickname: this.searchForm.nickname,
        pageSize: this.pageSize,
        pageNum: pageNum,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(1)
    },
    handleCurrentChange(pageNum){
      this.getDataList(pageNum);
    }
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
